<template>
	<!-- 出租发布 -->
	<u-form :model="form" ref="uForm">
		<view class="image-list-box">
			<view style="margin-left: 30rpx;font-size: 40rpx;margin-top: 20rpx;">
				<span>卖房</span>
			</view>

			<u-card :show-head="false" :show-foot="false" padding="0" margin="20rpx" :border="false">
				<view slot="body">
					<u-form-item style="margin-top: 20rpx;" prop="roomTitle">
						<view style="margin-left: 10rpx;">
							<u-input placeholder="请输入房子标题（如出租xx花园三房两厅两卫）" placeholder-style="color: #c0c4cc;" v-model="form.roomTitle" type="textarea"
							 :border="false" :auto-height="true" height="40rpx" :clearable="false" />
						</view>
					</u-form-item>
					<u-form-item style="margin-top: 20rpx;" prop="roomDescribe">
						<view style="margin-left: 10rpx;">
							<u-input placeholder="请输入房子描述（如近地铁，阳光好等）" placeholder-style="color: #c0c4cc;" v-model="form.roomDescribe" type="textarea"
							 :border="false" :auto-height="true" height="40rpx" :clearable="false" />
						</view>
					</u-form-item>
					<u-form-item style="margin-left: 28rpx;">
						<u-row :gutter="20">
							<u-upload :max-size="1 * 1024 * 1024" max-count="9" :action="action" :file-list="form.imageLists" :show-tips="false"
							 @on-remove="onRemove" :auto-upload="false" ref="uUpload"></u-upload>
						</u-row>
					</u-form-item>
				</view>
			</u-card>

			<view>
				<u-cell-group>
					<u-form-item prop="roomAddress">
						<u-cell-item title="位置" :arrow="false">
							<view style="width: 100%; padding-left: 360rpx;">
								<u-input input-align="right" placeholder="请输入地址精确到门牌号" v-model="form.roomAddress" :clearable="false"></u-input>
							</view>
						</u-cell-item>
					</u-form-item>
					<u-form-item prop="roomType">
						<u-cell-item title="户型" :value="form.roomType" @click="isShowSelectType = true"></u-cell-item>
						<u-select v-model="isShowSelectType" mode="mutil-column" :list="roomTypeList" @confirm="selectRoomType"
						 :safe-area-inset-bottom="true"></u-select>
					</u-form-item>
					<u-form-item prop="roomLevel">
						<u-cell-item title="楼层" :value="form.roomLevel" @click="isShowRoomLevel = true"></u-cell-item>
						<u-keyboard ref="uKeyboard" :tips="roomLevelTip + level" @backspace="backRoomLevel()" @change="roomLevelChange"
						 @confirm="levelConfirm" mode="number" :dot-enabled="false" v-model="isShowRoomLevel" :cancelBtn="false"
						 :safe-area-inset-bottom="false"></u-keyboard>
					</u-form-item>
					<u-form-item prop="roomArea">
						<u-cell-item title="面积" :value="form.roomArea" @click="isShowRoomArea = true"></u-cell-item>
						<u-keyboard ref="uKeyboard" :tips="roomAreaTip + area" @backspace="backRoomArea" @change="roomAreaChange"
						 @confirm="areaConfirm" mode="number" v-model="isShowRoomArea" :cancelBtn="false" :safe-area-inset-bottom="false"></u-keyboard>
					</u-form-item>
					<u-form-item prop="roomMoney">
						<u-cell-item title="出售价格" :value="form.roomMoney" @click="isShowRoomMoney = true"></u-cell-item>
						<u-keyboard ref="uKeyboard" :tips="roomMoneyTip + money" @backspace="backRoomMoney" @change="roomMoneyChange"
						 @confirm="moneyConfirm" mode="number" v-model="isShowRoomMoney" :cancelBtn="false" :safe-area-inset-bottom="false"></u-keyboard>
					</u-form-item>
					<u-form-item prop="phone">
						<u-cell-item title="电话" :arrow="false">
							<view style="width: 100%; padding-left: 360rpx;">
								<u-input input-align="right" placeholder="请输入联系电话" v-model="form.phone" :clearable="false"></u-input>
							</view>
						</u-cell-item>
					</u-form-item>
					<u-form-item prop="keyPosition">
						<u-cell-item title="钥匙在哪" :arrow="true" :value="form.keyPosition" @click="isShowKey = true">
							<!-- <view style="width: 100%; padding-left: 360rpx;">
								<u-input input-align="right" placeholder="请输入联系电话" v-model="form.keyPosition" :clearable="false"></u-input>
							</view> -->
						</u-cell-item>
						<u-popup v-model="isShowKey" mode="bottom" height="500rpx" :safe-area-inset-bottom="true">
							<keyPition @canlelCon="canlelCon"></keyPition>
						</u-popup>

					</u-form-item>
					<u-cell-item title="更多信息" :value="moreInfo" @click="gotoMoreRoomInfo"></u-cell-item>
				</u-cell-group>
			</view>

			<view style="height: 300rpx;margin-top: 20rpx;">
				<u-button class="subBt" shape="circle" :custom-style="{'backgroundColor': '#95ff00','width': '300rpx'}" @click="subHouseInfo">确认发布</u-button>
			</view>

			<u-toast ref="uToast" />
		</view>
	</u-form>

</template>

<script>
	import {
		uploadImage
	} from '../../utils/uploadFile.js'
	import keyPition from './keyPosition.vue'
	export default {
		data() {
			return {
				action: 'https://laidehao.com:8443/v1/file/images',
				form: {
					roomDescribe: '',
					roomTitle: '',
					roomAddress: '',
					roomType: '',
					roomMoney: '',
					roomArea: '',
					roomLevel: '',
					phone: '',
					keyPosition: '',
					imageLists: []
				},
				rules: {
					roomTitle: [{
						required: true,
						message: '房屋标题不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					roomDescribe: [{
						required: true,
						message: '房屋描述不能为空',
						// 可以单个或者同时写两个触发验证方式 
						trigger: ['change', 'blur'],
					}],
					roomAddress: [{
						required: true,
						message: '请输入详细地址',
						trigger: 'change'
					}],
					roomType: [{
						required: true,
						message: '请输入房屋户型',
						trigger: 'change'
					}],
					roomMoney: [{
						required: true,
						message: '房屋租金不能为空',
						trigger: 'change'
					}],
					roomArea: [{
						required: true,
						message: '请输入房屋面积',
						trigger: 'change'
					}],
					roomLevel: [{
						required: true,
						message: '请输入房屋楼层',
						trigger: 'change'
					}],
					phone: [{
						required: true,
						message: '请输入联系电话',
						trigger: 'change'
					}],
					keyPosition: [{
						required: true,
						message: '请输入钥匙地址',
						trigger: 'change'
					}]
					// imageLists: [{
					// 	required: true,
					// 	message: '请选择图片',
					// 	trigger: 'change'
					// }]
				},
				isShowKey: false,
				isShowSelectType: false,
				isShowRoomMoney: false,

				roomMoneyTip: '出售价格：',
				money: '',
				isShowRoomArea: false,

				roomAreaTip: '平米：',
				area: '',
				isShowRoomLevel: false,

				roomLevelTip: '楼层：',
				level: '',
				
				positionKey: '',
				roomTypeList: [
					[{
						value: '0',
						label: '0室'
					}, {
						value: '1',
						label: '1室'
					}, {
						value: '2',
						label: '2室'
					}, {
						value: '3',
						label: '3室'
					}, {
						value: '4',
						label: '4室'
					}, {
						value: '5',
						label: '5室'
					}, {
						value: '6',
						label: '6室'
					}],
					[{
						value: '7',
						label: '0厅'
					}, {
						value: '8',
						label: '1厅'
					}, {
						value: '9',
						label: '2厅'
					}, {
						value: '10',
						label: '3厅'
					}],
					[{
						value: '11',
						label: '0卫'
					}, {
						value: '12',
						label: '1卫'
					}, {
						value: '13',
						label: '2卫'
					}, {
						value: '14',
						label: '3卫'
					}]
				],

				selectTowards: [{
					name: '丰富信息,出租更快速',
					isSelect: true
				}],
				tagList: [],
				deviceList: [],
				liveInTime: ''
			};
		},
		watch: {
			'form.phone': function(newValue, oldvalue) {
				if (newValue.length > 11) {
					wx.showToast({
						title: '电话号码输入不正确',
						icon: 'none',
						duration: 1000
					})
					this.form.phone = oldvalue
					// console.log("this.orderTel", this.form.phone)
				}
			}
		},
		computed: {
			onRemove(item, list) {
				// console.log(item)
			},
			moreInfo() {
				var moreInfoString = ''
				var i = 0
				this.selectTowards.forEach(item => {
					if (item.isSelect) {
						moreInfoString += item.name
					}
				})
				this.deviceList.forEach(item => {
					if (item.isSelect) {
						// i++
						// if (i > 2) {
						// 	moreInfoString += '...'
						// 	return
						// }
						moreInfoString += '/' + item.name
					}
				})
				this.tagList.forEach(item => {
					if (item.isSelect) {
						// i++
						// if (i > 2) {
						// 	moreInfoString += '...'
						// 	return
						// }
						moreInfoString += '/' + item.name
					}
				})
				if (this.liveInTime != '')
					moreInfoString += '/' + this.liveInTime
				return moreInfoString.substr(0, 11) + '...'
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		methods: {
			gotoMoreRoomInfo() {
				wx.navigateTo({
					url: 'moreRoomInfo?selectTowards=' + JSON.stringify(this.selectTowards) + "&tagList=" + JSON.stringify(this.tagList) +
						"&deviceList=" + JSON.stringify(this.deviceList)
				})
			},
			//删除照片
			DelImg(item) {
				// console.log(item)
				for (var i = 0; i < this.form.imageLists.length; i++) {
					if (this.form.imageLists[i].src == item.src) {
						this.form.imageLists.pop(item)
					}
				}
				// console.log("删除后")
				// console.log(this.form.imageLists)
			},
			//确认发布房源
			subHouseInfo() {
				this.$refs.uForm.validate(async valid => {
					if (valid) {
						// console.log('验证通过');
						//判断是否选择了设置信息
						if (this.moreInfo == '丰富信息,出租更快速') {
							wx.showToast({
								title: '请选择更多信息',
								icon: 'none',
								duration: 1000
							})
							return
						}
						//传入房屋的非图片信息
						var tempFilePaths = this.$refs.uUpload.lists
						// console.log("图片")
						// console.log(tempFilePaths)
						if (tempFilePaths.length == 0) {
							wx.showToast({
								title: '请选择图片',
								icon: 'none',
								duration: 1000
							})
							return
						}

						var reg = /^1([358][0-9]|4[01456879]|6[2567]|7[0135678]|9[012356789])[0-9]{8}$/
						if(!reg.test(this.form.phone)){
							wx.showToast({
								title: '电话格式错误！',
								icon: 'none',
								duration: 1000
							})
							return
						}
						
						var toward = ""
						//传递添加的房屋信息
						this.selectTowards.forEach(item => {
							if (item.isSelect) {
								toward = item.name
							}
						})
						var d = null
						if (this.liveInTime == '随时可入住') {
							d = null
						} else {
							d = new Date(parseInt(this.liveInTime.split('-')[0]), parseInt(this.liveInTime.split('-')[1]) - 1, parseInt(
								this.liveInTime
								.split('-')[2]), 8, 0, 0, 0);
						}
						
						// var title = this.form.roomAddress + '·' + this.form.roomType + '·' + "无中介费"
						var price = this.form.roomMoney.substr(0,this.form.roomMoney.length-1)/10000 + '万元'
						// console.log('price',price)
						var house = {
							"address": this.form.roomAddress,
							"area": this.form.roomArea,
							"checkInTime": d,
							"description": this.form.roomDescribe,
							"doorModel": this.form.roomType,
							"floor": this.form.roomLevel,
							"methods": "直售",
							"price": price,
							"status": 0,
							"title": this.form.roomTitle,
							"phone": this.form.phone,
							"keyPosition": this.positionKey,
							"toward": toward,
							"type": 1,
						}
						// console.log("house")
						// console.log(house)
						var houseDeviceList = []
						var houseDevice = {}

						this.deviceList.forEach(item => {
							if (item.isSelect) {
								houseDeviceList.push({
									"deviceId": item.id,
									"isHas": 1
								})
							} else {
								houseDeviceList.push({
									"deviceId": item.id,
									"isHas": 0
								})
							}
						})
						// console.log(houseDeviceList)
						var houseTagList = []
						var houseTag = {}
						this.tagList.forEach(item => {
							if (item.isSelect) {
								houseTag = {
									"tagId": item.id
								}
								houseTagList.push(houseTag)
							}
						})
						// console.log(houseTagList)

						//上传房屋的图片
						var houseImageList = []
						var houseImage = {}

						// let res = this.$upLoadFile({
						// 	url: '/v1/house',
						// 	tempFilePaths: tempFilePaths
						// })
						var res = await uploadImage({
							url: '/v1/file/images',
							tempFilePaths: tempFilePaths
						})

						// console.log("图片", res)
						// console.log(res)
						res.forEach(item => {
							houseImage = {
								"address": item.data[0]
							}
							houseImageList.push(houseImage)
						})

						// console.log(houseImageList)

						//提交房屋信息
						let houseInfo = await this.$request({
							url: '/v1/house',
							method: 'POST',
							data: {
								"house": house,
								"houseDeviceList": houseDeviceList,
								"houseImageList": houseImageList,
								"houseTagList": houseTagList
							}
						})
						// console.log(houseInfo)
						if (!houseInfo.isSuccess) {
							wx.showToast({
								title: '发布失败',
								icon: 'none',
								duration: 2000,
							})
						} else {
							//页面跳转相当于
							// wx.showToast({
							// 	title: '等待管理员审核',
							// 	icon: 'success',
							// 	duration: 3000,
							// 	success() {
							// 		wx.switchTab({
							// 			url: '/pages/ownerPage/ownerPage'
							// 		})
							// 	}
							// })
							this.$refs.uToast.show({
								title: '发布成功\n请等待管理员审核',
								type: 'success',
								callback(){
									wx.switchTab({
										url: '/pages/ownerPage/ownerPage'
									})
								} 
							})
						}
					} else {
						console.log('验证失败');
					}
				});
			},
			canlelCon(value) {
				// console.log(JSON.stringify(value))
				this.isShowKey = value.isShowKey
				this.positionKey = value.keyPosition
					this.form.keyPosition = value.keyPosition.substr(0, 11) + '...'
			},
			//添加图片
			addImages() {
				var list = []
				var that = this
				wx.chooseImage({
					success: function(res) {
						console.log(res);
						count: 6; //限制选择数量
						// console.log(res.tempFilePaths) //打印获取到图片的临时地址
						let size = 0;
						for (var a in res.tempFiles) {
							size += res.tempFiles[a].size
						}
						for (var i = 0; i < res.tempFilePaths.length; i++) {
							that.form.imageLists.push({
								src: res.tempFilePaths[i]
							})
						}

						// console.log(that.form.imageLists)
						if (size < 1048576) {
							console.log('上传')
							//循环上传	
						} else {
							wx.showToast({
								title: '你选中的图片超过1M！',
								icon: 'none'
							})
						}
					}
				})

			},
			//selectRoomRype
			selectRoomType(e) {
				this.form.roomType = ''
				e.forEach((item) => {
					this.form.roomType = this.form.roomType + item.label
				})
			},
			roomMoneyChange(e) {
				this.form.roomMoney = ''

				if (this.money.length < 1000000000) {
					this.money += e
				}
				this.form.roomMoney = this.money + '元'
			},
			moneyConfirm(e) {
				// console.log("确认")
				this.form.roomMoney = this.money + '元'
			},
			backRoomMoney(e) {
				// console.log("退格")
				if (this.money.length > 0) this.money = this.money.substr(0, this.money.length - 1);
				if (this.money.length === 0) {
					this.form.roomMoney = '0元'
				} else {
					this.form.roomMoney = this.money + '元'
				}

			},
			roomAreaChange(e) {
				this.form.roomArea = ''
				this.area += e
				this.form.roomArea = this.area + '平米'
			},
			areaConfirm(e) {
				console.log("确认")
				this.form.roomArea = this.area + '平米'
			},
			backRoomArea(e) {
				// console.log("退格")
				if (this.area.length > 0) this.area = this.area.substr(0, this.area.length - 1);

				if (this.area.length === 0) {
					this.form.roomArea = '0平米'
				} else {
					this.form.roomArea = this.area + '平米'
				}
			},
			roomLevelChange(e) {
				this.form.roomLevel = ''
				this.level += e
				this.form.roomLevel = this.level + '楼'
			},
			levelConfirm(e) {
				// console.log("确认")
				this.form.roomLevel = this.level + '楼'
			},
			backRoomLevel(e) {
				// console.log("退格")
				if (this.level.length > 0) this.level = this.level.substr(0, this.level.length - 1);

				if (this.level.length === 0) {
					this.form.roomLevel = '0楼'
				} else {
					this.form.roomLevel = this.level + '楼'
				}
			}
		},
		components: {
			keyPition
		}
	}
</script>

<style>
	.cell-item-box {
		align-items: center;
		position: relative;
		box-sizing: border-box;
		width: 100%;
		padding: 13px 17px;
		font-size: 14px;
		height: 108rpx;
		color: #606266;
		border: 0rpx solid #e4e7ed;
	}

	.img {
		position: relative;
		display: inline-block;
		vertical-align: top;
	}

	.close {
		position: absolute;
		right: 10rpx;
		background-color: #FF0000;
		color: #fff;
	}
</style>
